package org.example.ai04.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.ai04.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT认证过滤器
 * 拦截所有HTTP请求，验证JWT令牌并设置认证上下文
 * 继承自OncePerRequestFilter，确保每个请求只经过一次过滤
 * 在Spring Security过滤器链中位于UsernamePasswordAuthenticationFilter之前
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    // 日志记录器
    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
    
    // 注入JWT工具类，用于生成和验证JWT令牌
    @Autowired
    private JwtUtil jwtUtil;

    // 注入自定义用户详情服务，用于加载用户信息
    @Autowired
    private CustomUserDetailsService userDetailsService;

    /**
     * 执行过滤操作，验证JWT令牌并设置安全上下文
     * @param request HTTP请求对象
     * @param response HTTP响应对象
     * @param filterChain 过滤器链
     * @throws ServletException Servlet异常
     * @throws IOException IO异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        // 从请求头中获取Authorization信息
        String authHeader = request.getHeader("Authorization");
        String token = null;
        String username = null;
        
        // 检查Authorization头是否存在且以Bearer开头
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            // 提取JWT令牌
            token = authHeader.substring(7);
            try {
                // 从令牌中提取用户名
                username = jwtUtil.extractUsername(token);
            } catch (Exception e) {
                logger.error("无法从token中提取用户名", e);
            }
        }
        
        // 如果用户名不为空且当前没有认证信息
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 加载用户详情
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            
            // 验证令牌是否有效
            if (jwtUtil.validateToken(token, userDetails.getUsername())) {
                // 创建认证令牌并设置详细信息
                UsernamePasswordAuthenticationToken authToken = 
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 设置认证上下文
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }
        
        // 继续过滤器链
        filterChain.doFilter(request, response);
    }
}